<template>
  <div class="wrapper">
    <el-table :data="tableData" style="width:fit-content; min-width: 100%;">
      <el-table-column type="index" label="序号" width="80" />
      <el-table-column prop="ruleName" label="规则名称" width="auto" />
      <el-table-column prop="ruleType" label="还款规则" width="auto">
        <template #default="scope">
          {{ getRuleTypeText(scope.row.ruleType) }}
        </template>
      </el-table-column>
      <el-table-column prop="useNumber" label="使用次数" width="auto" />
      <el-table-column label="操作" style="width: fit-content;" width="auto">
        <template #default="scope">
          <el-button size="small" @click="checkRepay(scope.$index)">查看</el-button>
          <el-button v-if="showEditDelete" size="small" type="primary" @click="editRepay(scope.$index)"
            :class="{ hidden: !showEditDelete }" :disabled="scope.row.useNumber >= 1">修改</el-button>
          <el-button v-if="showEditDelete" size="small" type="danger" @click="handleDelete(scope.$index)"
            :class="{ hidden: !showEditDelete }" :disabled="scope.row.useNumber >= 1">删除</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <el-dialog v-model="dialogVisible" title="方案详细信息" width="40%">
      <el-form :model="repaymentModel" label-width="120px" style="padding-right: 30px">
        <el-form-item label="还款规则类型" prop="ruleType">
          <el-radio-group v-model="repaymentModel.ruleType" :disabled="!enableTOEidt">
            <el-radio :label="0">一次还清</el-radio>
            <el-radio :label="1">等额分期</el-radio>
            <el-radio :label="2">阶段还款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="还款规则名称" prop="ruleName">
          <el-input v-model="repaymentModel.ruleName" :disabled="!enableTOEidt"></el-input>
        </el-form-item>
        <template v-if="repaymentModel.ruleType != 2">
          <el-form-item label="本金占比" prop="principalRatio">
            <el-input-number :min="0" v-model="repaymentModel.principalRatio" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="利息占比" prop="interestRatio">
            <el-input-number :min="0" v-model="repaymentModel.interestRatio" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="滞纳金占比" prop="lateFeeRatio">
            <el-input-number :min="0" v-model="repaymentModel.lateFeeRatio" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="违约金占比" prop="damageRatio">
            <el-input-number :min="0" v-model="repaymentModel.damageRatio" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="罚息占比" prop="defaultInterestRatio">
            <el-input-number :min="0" v-model="repaymentModel.defaultInterestRatio" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="其他金额占比" prop="otherAmountsRatio">
            <el-input-number :min="0" v-model="repaymentModel.otherAmountsRatio" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="还款时间" prop="repaymentTime">
            <el-input-number :min="0" v-model="repaymentModel.repaymentTime" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>天</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="分期次数" prop="numberOfInstallments">
            <el-input-number :min="0" v-model="repaymentModel.numberOfInstallments" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>次</span>
              </template>
            </el-input-number>
          </el-form-item>
          <el-form-item label="手续费" prop="commission">
            <el-input-number :min="0" v-model="repaymentModel.commission" :disabled="!enableTOEidt" controls-position="right">
              <template #suffix>
                <span>元</span>
              </template>
            </el-input-number>
          </el-form-item>
        </template>
        <template v-if="repaymentModel.ruleType === 2">
          <div class="stage-wrapper">
            <div v-for="(stageRepayment, index) in repaymentModel.stageRepayments" :key="index">
              <div class="stage-repayment">
                <div class="stage-repayment-header">
                  <div>第{{ index + 1 }}期</div>
                  <div>
                    <el-button @click="deleteStage(index)" v-if="index !== 0">删除</el-button>
                    <el-button @click="addStage(index)" v-if="index === repaymentModel.stageRepayments.length - 1">添加</el-button>
                  </div>
                </div>
                <div class="stage-repayment-footer">
                  <el-form-item label="本金占比" prop="principalRatio">
                    <el-input-number :min="0" v-model="stageRepayment.principalRatio" :disabled="!enableTOEidt" controls-position="right">
                      <template #suffix>
                        <span>%</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                  <el-form-item label="利息占比" prop="interestRatio">
                    <el-input-number :min="0"  v-model="stageRepayment.interestRatio" :disabled="!enableTOEidt" controls-position="right">
                      <template #suffix>
                        <span>%</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                  <el-form-item label="滞纳金占比" prop="lateFeeRatio">
                    <el-input-number :min="0"  v-model="stageRepayment.lateFeeRatio" :disabled="!enableTOEidt" controls-position="right">
                      <template #suffix>
                        <span>%</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                  <el-form-item label="违约金占比" prop="damageRatio">
                    <el-input-number :min="0"  v-model="stageRepayment.damageRatio" :disabled="!enableTOEidt" controls-position="right">
                      <template #suffix>
                        <span>%</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                  <el-form-item label="罚息占比" prop="defaultInterestRatio">
                    <el-input-number :min="0"  v-model="stageRepayment.defaultInterestRatio" :disabled="!enableTOEidt" controls-position="right">
                      <template #suffix>
                        <span>%</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                  <el-form-item label="其他金额占比" prop="otherAmountsRatio">
                    <el-input-number :min="0"  v-model="stageRepayment.otherAmountsRatio" :disabled="!enableTOEidt" controls-position="right">
                      <template #suffix>
                        <span>%</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                  <el-form-item label="还款时间" prop="repaymentTime">
                    <el-input-number :min="0"  v-model="stageRepayment.repaymentTime" :disabled="!enableTOEidt" controls-position="right">
                      <template #suffix>
                        <span>天</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                  <el-form-item label="手续费" prop="commission">
                    <el-input-number :min="0"  v-model="stageRepayment.commission" :disabled="!enableTOEidt" controls-position="right">
                      <template #suffix>
                        <span>元</span>
                      </template>
                    </el-input-number>
                  </el-form-item>
                </div>
              </div>
            </div>
          </div>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancle">关闭</el-button>
          <el-button type="primary" v-if="enableTOEidt" @click="saveRepayment()" > 提交 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, watch, Ref } from 'vue'
import { getRepaymentListByInsId } from '@/axios/case/repaymentReq'
import Repayment from "@/types/response/repayment"
import StageRepayment from "@/types/response/stageRepayment"
import useApplicantStore from '@/stores/applicantStore'
import {modifyRepaymentPlan,deleteRepaymentById} from '@/axios/case/repaymentReq'
import Notice from '@/utils/notice'

const applicantStore = useApplicantStore()

const tableData = ref([])
/* const testData = [
  { ruleName: '规则1', ruleType: 0, useNumber: 0 },
  { ruleName: '规则2', ruleType: 1, useNumber: 5 },
  { ruleName: '规则3', ruleType: 0, useNumber: 20 },
  { ruleName: '规则4', ruleType: 1, useNumber: 15 },
  { ruleName: '规则5', ruleType: 2, useNumber: 8 }
];
tableData.value = testData; */
// 新增 props 属性
const props = defineProps({
  showEditDelete: {
    type: Boolean,
    default: true
  },
  key:{
    type: Number,
    default: 0
  }
})
const getRuleTypeText = (ruleType: number) => {
  switch (ruleType) {
    case 0:
      return '一次还清';
    case 1:
      return '等额分期';
    case 2:
      return '阶段还款';
    default:
      return '未知类型';
  }
}
const deleteStage = (index) => {
  if (index != 0) {
    for (let i = index + 1; i < repaymentModel.stageRepayments.length; i++) {
      repaymentModel.stageRepayments[i].order--
    }
    repaymentModel.stageRepayments.splice(index, 1)
  }
}
const addStage = (index) => {
  let stage = reactive(new StageRepayment())
    stage.repaymentId = repaymentModel.repaymentId
    stage.order = index + 1
    stage.principalRatio = 0
    stage.interestRatio = 0
    stage.lateFeeRatio = 0
    stage.damageRatio = 0
    stage.defaultInterestRatio = 0
    stage.otherAmountsRatio = 0
    stage.repaymentTime = 0
    stage.commission = 0
    repaymentModel.stageRepayments.push(stage)
}
const handleView = (index, row) => {
  console.log('查看', index, row)
  // 在这里添加查看逻辑
}

const handleEdit = (index, row) => {
  console.log('修改', index, row)
  // 在这里添加修改逻辑
}

const handleDelete = async(index) => {
  console.log("*********")
  console.log(tableData.value[index].repaymentId)
  let repaymentId = tableData.value[index].repaymentId
 try{
    await deleteRepaymentById(repaymentId)
    const index = tableData.value.findIndex(item => item.repaymentId === repaymentModel.repaymentId);
    tableData.value.splice(index, 1)
    Notice.success("删除成功")
    await getRepaymentListByInsId(applicantStore.applicantInsId)
 }
 catch(error){
  Notice.error("删除失败")
 }
}
const dialogVisible = ref(false)
const repaymentModel = reactive(new Repayment())
const enableTOEidt = ref(false)
onMounted(async () => {
  repaymentModel.applicationInstitutionId = applicantStore.applicantInsId
  try {
    const response = await getRepaymentListByInsId(applicantStore.applicantInsId)
    tableData.value = response
  } catch (error) {
    console.error('获取还款列表失败', error)
  }
})
const cancle = () => {
  dialogVisible.value = false
  repaymentModel.ruleType = 0
  repaymentModel.ruleName = ''
  repaymentModel.principalRatio = 0
  repaymentModel.interestRatio = 0
  repaymentModel.lateFeeRatio = 0
  repaymentModel.damageRatio = 0
  repaymentModel.defaultInterestRatio = 0
  repaymentModel.otherAmountsRatio = 0
  repaymentModel.repaymentTime = 0
  repaymentModel.numberOfInstallments = 0
  repaymentModel.commission = 0
}
const checkRepay = (idx) => {
  dialogVisible.value = true
  enableTOEidt.value = false
  repaymentModel.ruleType = tableData.value[idx].ruleType
  repaymentModel.ruleName = tableData.value[idx].ruleName
  repaymentModel.principalRatio = tableData.value[idx].principalRatio
  repaymentModel.interestRatio = tableData.value[idx].interestRatio
  repaymentModel.lateFeeRatio = tableData.value[idx].lateFeeRatio
  repaymentModel.damageRatio = tableData.value[idx].damageRatio
  repaymentModel.defaultInterestRatio = tableData.value[idx].defaultInterestRatio
  repaymentModel.otherAmountsRatio = tableData.value[idx].otherAmountsRatio
  repaymentModel.repaymentTime = tableData.value[idx].repaymentTime
  repaymentModel.numberOfInstallments = tableData.value[idx].numberOfInstallments
  repaymentModel.commission = tableData.value[idx].commission

  repaymentModel.stageRepayments = tableData.value[idx].stageRepayments
}
const editRepay = (idx) => {
  dialogVisible.value = true
  enableTOEidt.value = true
  repaymentModel.repaymentId = tableData.value[idx].repaymentId
  repaymentModel.ruleType = tableData.value[idx].ruleType
  repaymentModel.ruleName = tableData.value[idx].ruleName
  repaymentModel.principalRatio = tableData.value[idx].principalRatio
  repaymentModel.interestRatio = tableData.value[idx].interestRatio
  repaymentModel.lateFeeRatio = tableData.value[idx].lateFeeRatio
  repaymentModel.damageRatio = tableData.value[idx].damageRatio
  repaymentModel.defaultInterestRatio = tableData.value[idx].defaultInterestRatio
  repaymentModel.otherAmountsRatio = tableData.value[idx].otherAmountsRatio
  repaymentModel.repaymentTime = tableData.value[idx].repaymentTime
  repaymentModel.numberOfInstallments = tableData.value[idx].numberOfInstallments
  repaymentModel.commission = tableData.value[idx].commission

  repaymentModel.stageRepayments = tableData.value[idx].stageRepayments
}
const saveRepayment = async () => {
  try {
    const data: Repayment = await modifyRepaymentPlan(repaymentModel);
    dialogVisible.value = false;
    // 更新 tableData 中对应的数据项
    const index = tableData.value.findIndex(item => item.repaymentId === repaymentModel.repaymentId);
    if (index !== -1) {
      tableData.value[index] = { ...data };
    } else {
      tableData.value.push(data);
    }
    Notice.success('修改成功')
  } catch (error) {
    console.error('修改还款计划失败', error)
    Notice.error('修改还款计划失败')
  }
}
watch(repaymentModel, () => {
  if (repaymentModel.ruleType === 2) {
    if (repaymentModel.stageRepayments === null || repaymentModel.stageRepayments.length === 0) {
      let stage = reactive(new StageRepayment())
      repaymentModel.stageRepayments = [stage]
    }
    if (repaymentModel.repaymentId === null) {
      repaymentModel.repaymentId = Math.floor(1000000 + Math.random() * 9000000)
    }
  }
})
</script>

<style>
.wrapper {
  width: 100%;
}

.el-table {
  border: 1px solid #ebeef5;
}

.el-table th,
.el-table td {
  text-align: center;
  padding: 10px;
}

.hidden {
  visibility: hidden;
}


.el-button {
  margin-right: 10px;
}

.stage-repayment {
  width: 90%;
  border: 1px solid #ebeef5;
  border-radius: 10px;
  margin: 20px auto;
}

.stage-wrapper {}

.stage-repayment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
}

.stage-repayment-footer {
  padding-right: 15px;
}
</style>